import { App, Configuration, ILifeCycle } from '@midwayjs/core';
import { Application } from 'egg';
import { join } from 'path';
import * as egg from '@midwayjs/web';
import * as staticFile from '@midwayjs/static-file';
import * as otel from '@ali/midway-otel';
import { spawn, spawnSync } from 'child_process';
import * as path from 'path';

@Configuration({
  imports: [
    egg,
    otel,
    staticFile,
  ],
  importConfigs: [join(__dirname, './config')],
})
export class ContainerLifeCycle implements ILifeCycle {
  @App()
  app: Application;

  async onReady() {
    // 初始化逻辑
    const nodePath = path.join(__dirname, '../node_modules/.bin/node');
    console.log('---------执行ohpm-repo install开始---------');
    spawnSync(nodePath, ['./bin/repo.js', 'install'], {
      stdio: 'inherit',
      cwd: path.join(__dirname, '../repo'),
    });
    console.log('---------执行ohpm-repo install完成---------');


    console.log('---------执行ohpm-repo start开始---------');
    const child = spawn(nodePath, ['./bin/repo.js', 'start'], {
      stdio: 'inherit', // 该选项会使得子进程的输出继承自父进程，从而可以在控制台中看到输出
      cwd: path.join(__dirname, '../repo'),
      env: {
        ...process.env,
        OHPM_REPO_DEPLOY_ROOT: '/mnt'
      }
    });
    child.on('error', (err) => {
      console.error('启动子进程失败:', err);
    });
    child.on('exit', (code, signal) => {
      if (code !== null) {
        console.log(`子进程退出，退出码 ${code}`);
      } else {
        console.log(`子进程被信号 ${signal} 终止`);
      }
    });
    console.log('---------执行ohpm-repo start完成---------');
  }

}
